package com.milhouz.quizzdroid;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

import android.content.ContentProviderClient;
import android.content.ContentValues;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import au.com.bytecode.opencsv.CSVReader;

import com.milhouz.quizzdroid.db.QuizzDroidConstants;
import com.milhouz.quizzdroid.db.QuizzDroidDbAPI;
import com.milhouz.quizzdroid.db.QuizzDroidProvider;

public class QuizzLoaderASyncTask extends AsyncTask<Integer, Integer, Long> {

	private final Context mContext;

	public QuizzLoaderASyncTask(Context context) {
		mContext = context;
	}

	@Override
	protected Long doInBackground(Integer... nbQuestions) {
		loadQuizzQuestions(nbQuestions[0]);
		return 0l;
	}

	/** Load Quizz Questions into the database */
	private void loadQuizzQuestions(int nbQuestionsLoaded) {
		if (nbQuestionsLoaded == 0) {
			Log.i(QuizzDroidConstants.TAG, "First quizz loader");
		} else {
			Log.i(QuizzDroidConstants.TAG, "Resume quizz loader from question n°" + nbQuestionsLoaded);
		}

		// Load Quizz data from csv file
		try {
			// Parse the CSV
			CSVReader reader = new CSVReader(new InputStreamReader(mContext.getAssets().open(QuizzDroidConstants.CSV_QUESTIONS_FILE), "UTF-8"), ';');
			String[] nextLine;

			// Add questions
			ContentValues values = new ContentValues();
			int csvLineNumber = 0;
			int curQuestionId = 1;
			int curCategoryId = 1;
			while ((nextLine = reader.readNext()) != null) {
				if (curQuestionId > nbQuestionsLoaded) {
					// Save category if exists
					curCategoryId = saveCategoryAndGetId(nextLine[1]);

					// Save the current question
					values.clear();
					values.put(QuizzDroidConstants.ID, curQuestionId);
					values.put(QuizzDroidConstants.COLUMN_NAME_QUESTION, nextLine[2]);
					values.put(QuizzDroidConstants.COLUMN_NAME_RESPONSE, nextLine[3]);
					values.put(QuizzDroidConstants.COLUMN_NAME_RESPONSE_NUMBER, "0");
					values.put(QuizzDroidConstants.COLUMN_NAME_CATEGORY_ID, curCategoryId);
					mContext.getContentResolver().insert(QuizzDroidProvider.QUESTIONS_URI, values);

					// Save the question potential responses
					for (int i = 3; i <= 6; i++) {
						values.clear();
						values.put(QuizzDroidConstants.COLUMN_NAME_QUESTION_ID, curQuestionId);
						values.put(QuizzDroidConstants.COLUMN_NAME_RESPONSE, nextLine[i]);
						if (i == 3) {
							values.put(QuizzDroidConstants.COLUMN_NAME_IS_GOOD_RESPONSE, 1);
						} else {
							values.put(QuizzDroidConstants.COLUMN_NAME_IS_GOOD_RESPONSE, 0);
						}
						mContext.getContentResolver().insert(QuizzDroidProvider.RESPONSES_URI, values);
					}
				}
				// Update question id and csv line number
				curQuestionId++;
				csvLineNumber++;
			}
		} catch (FileNotFoundException e) {
			Log.e(QuizzDroidConstants.TAG, "Questions file not found", e);
		} catch (IOException e) {
			Log.e(QuizzDroidConstants.TAG, "Error during Quiz questions file reading", e);
		} finally {
			Log.i(QuizzDroidConstants.TAG, "Quizz loader finished.");
		}
	}

	private int saveCategoryAndGetId(String categoryName) {
		int id = QuizzDroidDbAPI.getInstance().getCategoryId(mContext, categoryName);
		if (id == -1) {
			ContentProviderClient client = mContext.getContentResolver().acquireContentProviderClient(QuizzDroidProvider.CATEGORIES_URI);
			id = ((QuizzDroidProvider) client.getLocalContentProvider()).getCategoryMaxId();
			ContentValues values = new ContentValues();
			values.put(QuizzDroidConstants.ID, String.valueOf(++id));
			values.put(QuizzDroidConstants.COLUMN_NAME_LABEL, categoryName);
			mContext.getContentResolver().insert(QuizzDroidProvider.CATEGORIES_URI, values);
			return id;
		}
		return id;
	}

}
